package com.example.utils.download;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description: 文件下载至客户端
 * @Author runto
 * @Date 2023/10/13 23:34
 * @PackageName:com.example.utils.download
 * @ClassName: DownloadTemplate
 * @Version 1.0
 */
public class DownloadTemplate {
    private final static Logger log = LoggerFactory.getLogger(FileUtil.class);
    /**
     * 下载有模板的文件
     * @param request
     * @param response
     * @param templateFileName
     * @param aid_language
     * @throws Exception
     */
    public static void downLoad(HttpServletRequest request, HttpServletResponse response,
                                String templateFileName, String aid_language) throws Exception{
        FileInputStream fileInputStream = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        PrintWriter printWriter = null;
        try {

            String realPath = request.getSession().getServletContext().getRealPath("fileTemple");
            realPath = realPath + File.separator;
            log.info("模板路径:"+realPath+templateFileName);
            fileInputStream = new FileInputStream(realPath+templateFileName);
            inputStream = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[inputStream.available()];
            if(buffer.length>0){
                inputStream.read(buffer);
            }
            inputStream.close();

            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition",
                    "attachment;filename="+new String (templateFileName.getBytes("GBK"),"ISO8859-1"));
            outputStream = response.getOutputStream();
            outputStream.write(buffer);
            outputStream.flush();
        } catch (Exception e) {
            String resultMessage = e.getCause()==null?e.getMessage():e.getCause().getMessage();
            String message = null;
            if(!StringUtils.isBlank(aid_language)&&aid_language.startsWith("zh")){
                message = "下载文件失败，失败原因:"+resultMessage;
            }else{
                message = "Failure to download a file, a cause of failure："+resultMessage;
            }
            log.error("下载错误:"+message);
            response.setContentType("text/html;charset=utf-8");
            printWriter = response.getWriter();
            printWriter.write(message);
            printWriter.flush();
        }finally{
            if (inputStream != null) {
                inputStream.close();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }

    /**
     * @param response		相应
     * @param filePath		文件的路径
     * @param fileName		文件的名称
     * @param aid_language	语言（提示用的）
     * @param removeFile	是否删除源文件
     * @throws Exception
     */
    public static void downLoadFile(HttpServletResponse response,String filePath,
                                    String fileName,String aid_language,Boolean removeFile) throws Exception{
        log.info("下载开始");
        FileInputStream fileInputStream = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        PrintWriter printWriter = null;
        String realPath = filePath;
        try {
            realPath = realPath + File.separator;
            log.info("模板路径:"+realPath+fileName);
            fileInputStream = new FileInputStream(realPath+fileName);
            inputStream = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[inputStream.available()];
            if(buffer.length>0){
                inputStream.read(buffer);
            }
            inputStream.close();

            //是否删除源文件
            if(removeFile){
                File file = new File(realPath+fileName);
                if(file.exists()){
                    file.delete();
                }
            }

            //下载到客户端
            if(fileName.indexOf(".zip") != -1){
                response.setContentType("application/octet-stream");
            }else if(fileName.indexOf(".pdf") != -1){
                response.setContentType("application/pdf");
            }
            response.setHeader("Content-disposition",
                    "attachment;filename="+new String (fileName.getBytes("GBK"),"ISO8859-1"));
            outputStream = response.getOutputStream();
            outputStream.write(buffer);
            outputStream.flush();
        } catch (Exception e) {
            //删除源数据
            File file = new File(realPath+fileName);
            if(file.exists()){
                file.delete();
            }

            String resultMessage = e.getCause()==null?e.getMessage():e.getCause().getMessage();
            String message = null;
            if(!StringUtils.isBlank(aid_language)&&aid_language.startsWith("zh")){
                message = "下载文件失败，失败原因:"+resultMessage;
            }else{
                message = "Failure to download a file, a cause of failure："+resultMessage;
            }
            log.error(message);
            response.setContentType("text/html;charset=utf-8");
            printWriter = response.getWriter();
            printWriter.write(message);
            printWriter.flush();
        }finally{
            //删除源数据
            File file = new File(realPath+fileName);
            if(file.exists()){
                file.delete();
            }

            if (inputStream != null) {
                inputStream.close();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            if (printWriter != null) {
                printWriter.close();
            }
        }
        log.info("下载结束");
    }


    /**
     * 下载文件
     * @param request
     * @param response
     * @param templateFileName
     * @param aid_language

     * @throws Exception
     */
    public static void downLoadFile(HttpServletRequest request, HttpServletResponse response,
                                    String realPath,String aid_language,String templateFileName) throws Exception{
        log.debug("csc_realPath:"+realPath);
        log.debug("csc_aid_language:"+aid_language);
        log.debug("csc_templateFileName:"+templateFileName);
        FileInputStream fileInputStream = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        PrintWriter printWriter = null;
        try {

            log.info("模板路径:"+realPath);
            fileInputStream = new FileInputStream(realPath);
            inputStream = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            inputStream.close();
            templateFileName=templateFileName.split("\\.")[0]+"_"+getDateFormat(new Date(),YYYYMMDDHHMISS)+"."+templateFileName.split("\\.")[1];
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename="+new String (templateFileName.getBytes("GBK"),"ISO8859-1"));
            outputStream = response.getOutputStream();
            outputStream.write(buffer);
            outputStream.flush();
        } catch (Exception e) {
            log.error("err_csyz:", e);
            //String resultMessage = e.getCause()==null?e.getMessage():e.getCause().getMessage();
            String resultMessage = e.toString() + "模板路径:"+ realPath +"文件名：" + templateFileName+"\n fileInputStream: "+ fileInputStream
                    + "\n inputStream:"+ inputStream;
            String message = null;
            if(!StringUtils.isBlank(aid_language)&&aid_language.startsWith("zh")){
                message = "下载文件失败，失败原因:"+resultMessage;
            }else{
                message = "Failure to download a file, a cause of failure："+resultMessage;
            }
            log.error("下载错误:"+message);
            response.setContentType("text/html;charset=utf-8");
            printWriter = response.getWriter();
            printWriter.write(message);
            printWriter.flush();
        }finally{
            if (inputStream != null) {
                inputStream.close();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }

    public static final String YYYYMMDDHHMISS="yyyyMMddHHmmss";
    public static String getDateFormat(Date date, String pattern) {
        DateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }


}

